/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hbr;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Environment;
//import org.apache.log4j.Logger;

/**
 * Provides ORM through hibernate.
 *
 */
class AbstractORMImpl implements ORM {

    private static ORM inst = new AbstractORMImpl();
    private static SessionFactory sf;
//    private Logger log = Logger.getLogger(AbstractORMImpl.class);

    private AbstractORMImpl() {
        try {
            InitialContext ic = new InitialContext();
            sf = (SessionFactory) ic.lookup(HibernateHelper.getPropertyValue(Environment.SESSION_FACTORY_NAME));
        } catch (NamingException ex) {
            java.util.logging.Logger.getLogger(AbstractORMImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static ORM getInstance() {
        return inst;
    }

    public void saveOrUpdate(Object obj) {
        sf.getCurrentSession().saveOrUpdate(obj);
    }

    public Collection getAll(Class cl) {
        Criteria criteria = sf.getCurrentSession().createCriteria(cl);
        return criteria.list();
    }

    public Object getById(Class cl, Serializable id) {
        return sf.getCurrentSession().get(cl, id);
    }

    public void delete(Object obj) {
        sf.getCurrentSession().delete(obj);
    }

    public List getWith(String namedQuery, Collection<String> values) {

        Query q = sf.getCurrentSession().getNamedQuery(namedQuery);
        int i = -1;
        for (String value : values) {
            i++;
            q.setString(i, value);
        }
        return q.list();
    }

    public void update(Object obj) {
        sf.getCurrentSession().update(obj);
    }

    public Collection getWithList(String namedQuery, Collection<String> values) {
        Query q = sf.getCurrentSession().getNamedQuery(namedQuery);
        q.setParameterList(namedQuery, values);
        return q.list();
    }
    /*
    public void openSession() {
    s = sf.openSession();
    }

    public void closeSession() {
    s.close();
    sf.close();
    }
     * 
     */
}
